package cz.anime.ppro.beans;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import cz.anime.ppro.logic.EventComponent;
import cz.anime.ppro.logic.UserComponent;
import cz.anime.ppro.model.Event;

@Component
@ManagedBean
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class UserCreatedEventsAdministrationBean {

	private List<Event> usersEvents;
	
	@Autowired
	private EventComponent eventComponent;
	
	@Autowired
	private UserComponent userComponent;
	
	@PostConstruct
	public void init(){
		List<Event> events = eventComponent.getEvents();
		usersEvents = new ArrayList<Event>();
		for (Event event : events) {
			if (event.getWebuser().getId() != 0 && event.getWebuser().getId() == getUser()) usersEvents.add(event); 	
		}
	}
	
	public void deleteEvent(int eventId){
		
		Event event = eventComponent.getEvent(eventId);
		
		eventComponent.deleteEvent(event);
		usersEvents.remove(event);
		
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("/PPRO2/admin-my-events.jsf");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private int getUser(){
		return userComponent.getUserByNick(userComponent.getCurrentUsernameFromSession()).getId();
	}

	public List<Event> getUsersEvents() {
		return usersEvents;
	}

	public void setUsersEvents(List<Event> usersEvents) {
		this.usersEvents = usersEvents;
	}
}

